package com.cmonbaby.adapter.recycleview.utils;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.view.ViewGroup;

/**
 * 包装工具类
 * @author simon 2016-9-19 下午16:05:29
 * @since JDK1.8 SDK6.0.1
 * @version V2.3.4
 */
public class WrapperUtils {

    /** 占据的单元格回调 */
    public interface SpanSizeCallback {
        /** 返回值决定每个position上的item占据的单元格个数 */
        int getSpanSize(GridLayoutManager layoutManager, GridLayoutManager.SpanSizeLookup oldLookup, int position);
    }

    /**
     * 依附，绑定RecyclerView，在onCreateViewHolder()之后调用
     *
     * @param innerAdapter RecyclerView.Adapter
     * @param recyclerView RecyclerView
     * @param callback 占据的单元格回调，需要实现
     */
    public static void onAttachedToRecyclerView(RecyclerView.Adapter innerAdapter, RecyclerView recyclerView, final SpanSizeCallback callback) {
        innerAdapter.onAttachedToRecyclerView(recyclerView);

        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            final GridLayoutManager.SpanSizeLookup spanSizeLookup = gridLayoutManager.getSpanSizeLookup();

            // SpanSizeLookup是一个抽象类，而且仅有一个抽象方法getSpanSize
            // 这个方法的返回值决定了每个position上的item占据的单元格个数
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return callback.getSpanSize(gridLayoutManager, spanSizeLookup, position);
                }
            });
            gridLayoutManager.setSpanCount(gridLayoutManager.getSpanCount());
        }
    }

    /**
     * 网格布局，当前位置是header或者footer的位置，那么该item应该占据2个单元格，而不是正常情况下占据1个单元格<br />
     * setFullSpan方法来设置占领全部空间
     *
     * @param holder RecyclerView.ViewHolder
     */
    public static void setFullSpan(RecyclerView.ViewHolder holder) {
        ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();

        if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) {

            StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;

            // StaggeredGridLayoutManager.LayoutParams为我们提供了一个setFullSpan方法来设置占领全部空间
            p.setFullSpan(true);
        }
    }
}
